<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <div>
        <!--    查询功能-->
        <div class="center">
            <div class="profile">
                <el-date-picker class="queryInp date-picker" v-model="queryData.date" :clearable="false"
                    @change="handleDateChange" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions" prefix-icon="el-icon-date" />
                <el-select v-model="joint" class="session-select queryInp" placeholder="全部节次" @change="changeSelect">
                    <el-option v-for="item in jointNum" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-input class="queryInp" v-model="queryData.applicant" @keyup.enter.native="select"
                    placeholder="请输入申请人姓名"></el-input>
                <el-input class="queryInp" v-model="queryData.classroom" @keyup.enter.native="select"
                    placeholder="请输入教室"></el-input>
                <el-input class="queryInp" v-model="queryData.applicantUnit" @keyup.enter.native="select"
                    placeholder="请输入申请单位"></el-input>
                <el-button type="primary" style="margin-left: 5px; height: 31.5px" icon="el-icon-search"
                    @click="select">查询</el-button>
            </div>
        </div>
        <el-table :data="formData" :header-cell-style="{ background: '#D3D3D3FF', color: '#555555' }">
            <el-table-column v-for="(e, i) in rowData" :key="i" :label="e.label" :width="e.width">
                <div slot-scope="scope" v-if="e.prop != 'session'">
                    <span>{{ scope.row[e.prop] }}</span>
                </div>
                <div slot-scope="scope" v-else>
                    <span>{{ formatSession(scope.row[e.prop]) }}</span>
                </div>
            </el-table-column>
            <el-table-column prop="operate" label="操作" width="200">
                <template slot-scope="scope">
                    <el-popconfirm v-if="scope.row.status != 1" confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red"
                        title="确定审批此教室预约吗？" @confirm="update(scope.row, 1)" style="margin-right: 5px">
                        <el-button slot="reference" size="small" type="success">通过</el-button>
                    </el-popconfirm>
                    <el-popconfirm v-if="scope.row.status != 2" confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red"
                        title="确定驳回此教室预约吗？" @confirm="update(scope.row, 2)" style="margin-right: 5px">
                        <el-button slot="reference" size="small" type="info" plain>驳回</el-button>
                    </el-popconfirm>
                    <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red"
                        title="确定删除此教室预约吗？" @confirm="del(scope.row.id)">
                        <el-button slot="reference" size="small" type="danger">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination v-show="queryData.total > 0" :total="queryData.total" :page.sync="queryData.pageNum"
            :limit.sync="queryData.pageSize" class="list-pagination" @pagination="getList" />
    </div>
</template>

<script>
import { getBookCourseList, deleteCourseById, updateCourseStatus, getStatus } from "@/api/classroomReservation.js"
export default {
    data() {
        return {
            pickerOptions: {
                disabledDate(time) {
                    const now = new Date()
                    const currentDay = now.getDay()
                    if (currentDay === 6) now.setDate(now.getDate() + 2)
                    else if (currentDay === 0) now.setDate(now.getDate() + 1)
                    return time < now.setHours(0, 0, 0, 0)
                }
            },
            queryData: {
                date: "",
                classStart: "",
                classEnd: "",
                applicant: "",
                classroom: "",
                applicantUnit: "",
                total: 0,
                pageNum: 1,
                pageSize: 10
            },
            joint: "",
            rowData: [
                // {
                //     prop: "id",
                //     label: "id",
                //     width: "50"
                // },
                {
                    prop: "date",
                    label: "预约日期",
                    width: "150"
                },
                {
                    prop: "classroom",
                    label: "预约地点",
                    // width: "200"
                },
                {
                    prop: "peopleNum",
                    label: "预约人数",
                    width: "100"
                },
                {
                    prop: "session",
                    label: "课程节次",
                    width: "100"
                },
                {
                    prop: "applicantUnit",
                    label: "申请单位",
                    // width: "100"
                },
                {
                    prop: "applicant",
                    label: "预约人",
                    width: "100"
                },
                {
                    prop: "contactInformation",
                    label: "预约电话",
                },
                {
                    prop: "statusName",
                    label: "审核状态",
                    width: "100"
                },
            ],
            jointNum: [
                { label: "全部节次", value: "" },
                { label: "1-2节", value: "1-2" },
                { label: "3-4节", value: "3-4" },
                { label: "5-6节", value: "5-6" },
                { label: "7-8节", value: "7-8" },
                { label: "9-10节", value: "9-10" },
                { label: "11-12节", value: "11-12" }
            ],
            formData: [],
            status: []
        }
    },
    async created() {
        await this.getStatus()
        this.queryData.date = this.getDefaultDate()
        this.select()
    },
    methods: {
        handleDateChange(value) {
            if (!value) this.queryData.date = this.getDefaultDate()
        },
        // 获取默认日期
        getDefaultDate() {
            const now = new Date();
            const currentDay = now.getDay(); // 0（周日）到 6（周六）

            // 如果是周六或周日，计算下周一的日期
            if (currentDay === 6) {
                now.setDate(now.getDate() + 2);
            } else if (currentDay === 0) {
                now.setDate(now.getDate() + 1);
            }

            // 格式化日期为 YYYY-MM-DD，确保月和日是两位数
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
            const day = String(now.getDate()).padStart(2, '0');

            return `${year}-${month}-${day}`;
        },
        select() {
            this.queryData.pageNum = 1
            this.getAvailableList()
        },
        // 获取可预约列表
        async getAvailableList() {
            try {
                const res = await getBookCourseList(this.queryData.pageNum, this.queryData.pageSize)
                this.formData = res.list.records
                this.queryData.total = res.list.total
            } catch (error) {
                console.error("获取空闲教室失败:", error)
            }
        },
        // 处理节次选择
        changeSelect(val) {
            if (val) {
                const [start, end] = val.split("-")
                this.queryData.classStart = start
                this.queryData.classEnd = end
            } else {
                this.queryData.classStart = ""
                this.queryData.classEnd = ""
            }
        },
        // 格式化节次显示
        formatSession(session) {
            return session?.replace(/[一二三四五六七日[\]]/g, '').replace(',', ' - ') || ''
        },
        getList(e) {
            this.queryData.pageNum = e.page
            this.queryData.pageSize = e.limit
            this.getAvailableList()
        },
        update(e, status) {
            let data = {...e}
            data.status = status
            updateCourseStatus(e.id, data).then((res) => {
                if (res.code === 20000) {
                    this.$message({
                        message: "审批成功",
                        type: "success",
                    });
                    this.select();
                } else {
                    this.$message({
                        message: "审批失败",
                        type: "error",
                    });

                }
            });
        },
        getStatus() {
            return new Promise((resolve) => {
                getStatus().then(res => {
                    this.status = res.bookCourseEnum
                    resolve()
                })
            })
        },
        del(e) {
            deleteCourseById(e).then(res => {
                if (res.code === 20000) {
                    this.rec
                    this.$message({
                        message: "取消预约成功",
                        type: "success",
                    });
                    this.select();
                } else {
                    this.$message({
                        message: "取消预约失败",
                        type: "error",
                    });
                }
            })
        },
    }
}
</script>

<style scoped>
.center {
    margin-bottom: 5px;
}

.queryInp {
    width: 200px;
    margin-right: 5px;
}
</style>